﻿// --------------------------------------------------------------------------------------------------------------------
// <summary>
//   Builds nested page list.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace App_Code.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Web.UI.HtmlControls;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using BlogEngine.Core;
	using System.Collections.Specialized;  // Needed for NameValueCollection

    /// <summary>
    /// Summary description for PageLinkMenu
    /// </summary>
    public class PageLinkMenu : Control
    {
	
	static PageLinkMenu()
        {
		    /// Start Step 15 PageLinkMenu ///
            BlogEngine.Core.Page.Saved += delegate { _Html = null; };
        }

        
	
        #region Properties

        private bool _ulIdSet = false;
        string _curPage = HttpUtility.UrlEncode(GetPageName(HttpContext.Current.Request.RawUrl.ToLower()));

        ///private string Html
        ///{
           /// get
            ///{
               /// HtmlGenericControl ul = BindPages();
                ///System.IO.StringWriter sw = new System.IO.StringWriter();
                ///ul.RenderControl(new HtmlTextWriter(sw));
                ///return sw.ToString();
           /// }
        ///}
		///

		//Start Step 16 PageLinkMenu //	
		
		 private string _Filter;
        public string Filter
        {
            get { return _Filter; }
            set { _Filter = value; }
        }
        private static object _SyncRoot = new object();
        private static NameValueCollection _Html;
        /// <summary>

        /// Caches the rendered HTML in the private field and first

        /// updates it when a post has been saved (new or updated).

        /// </summary>

        private NameValueCollection Html
        {
            get
            {
                if (_Html == null ||
                    (!String.IsNullOrEmpty(Filter) && _Html[Filter] == null))
                {
                    lock (_SyncRoot)
                    {
                        if (_Html == null ||
                            (!String.IsNullOrEmpty(Filter) && _Html[Filter] == null))
                        {
                            if (_Html == null)
                                _Html = new NameValueCollection();
                            HtmlGenericControl ul = BindPages();
                            System.IO.StringWriter sw = new System.IO.StringWriter();
                            ul.RenderControl(new HtmlTextWriter(sw));
                            _Html.Add(Filter, sw.ToString());
                        }
                    }
                }
                return _Html;
            }
        }
        #endregion
		
// End Step 16 PageLinkMenu//
		

       private HtmlGenericControl BindPages()

	{
       // recursivly get all children of the root page
       HtmlGenericControl ul = GetChildren(Guid.Empty);
            return ul;
     }

	   bool HasChildren(Guid pageId)
			{
				bool returnValue = false;

				    foreach (BlogEngine.Core.Page page in BlogEngine.Core.Page.Pages)
					  {
						if (page.ShowInList && page.IsPublished)
							{
							  if (page.Parent == pageId)
								{
								  returnValue = true;
									break;
								}
							}
					   }

			    return returnValue;
			}
			
	HtmlGenericControl GetChildren(Guid parentId)
        {
            HtmlGenericControl ul = new HtmlGenericControl("ul");

            if (!_ulIdSet)
            {
                ul.Attributes.Add("id", "menu-topmenu");
                ul.Attributes.Add("class", "menu");
                _ulIdSet = true;

				/// Need to add abilty to sort these pages ///
                /// AddMenuItem(ul, Resources.labels.home, "~/default.aspx");        ///
                /// AddMenuItem(ul, Resources.labels.archive, "~/archive.aspx");     /// 
            }

 // -------------------Start of--Main part-----------------------------------------------------------------------//			
			
			//  1.Is page to be shown? and is it published?
			//    2.If so Filter it out by the Menus  like "Head" "leftside"   
			//      3. Then Sort the pages
			//        4. Get the parent    not sure on what happens with 4. and 5.
            //          5. Then the child
			
      
             {
				
				  
					foreach (var page in BlogEngine.Core.Page.Pages.OrderBy(page => page.Pagesort))          /// 3. Sorts the pages
                        
                        if (String.IsNullOrEmpty(Filter) || page.Linkmenu.ToLower().StartsWith(_Filter.ToLower()))	 /// 2.Filters by LinkMenu 	


                        

                            if (page.ShowInList && page.IsPublished)
                    
                        {
					
				  
                           if (page.Parent == parentId)
                              {
									HtmlGenericControl li = new HtmlGenericControl("li");
									string pageName = HttpUtility.UrlEncode(GetPageName(page.RelativeLink.ToString().ToLower()));

									HtmlAnchor anc = new HtmlAnchor();
									anc.HRef = page.RelativeLink.ToString();
									anc.InnerHtml = page.Linkname;    // PageLinkMenu Step 20 Uses LinkName instead of title
									anc.Title = page.Description;

							if (pageName == _curPage)
								{
									anc.Attributes.Add("class", "current");
								}

                        li.Controls.Add(anc);

                        if (HasChildren(page.Id))
                        {
                            HtmlGenericControl subUl = GetChildren(page.Id);
                            li.Controls.Add(subUl);
                        }
                        ul.Controls.Add(li);
                    }
                }
            }

            return ul;
			
		}	
						
// -------------------End of--Main part-----------------------------------------------------------------------//	

        public override void RenderControl(HtmlTextWriter writer)
        {
            writer.Write(Html[Filter]);
            writer.Write(Environment.NewLine);
        }

        public static string GetPageName(string requestPath)
        {
            if (requestPath.IndexOf('?') != -1)
                requestPath = requestPath.Substring(0, requestPath.IndexOf('?'));
            return requestPath.Remove(0, requestPath.LastIndexOf("/") + 1).ToLower();
        }
    }
}